package cn.bdqn.hospital.dao.impl;

import cn.bdqn.hospital.dao.CommentDao;
import cn.bdqn.hospital.entity.Comment;
import cn.bdqn.hospital.utils.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
 * 评论的实现dao
 */
public class CommentDaoImpl implements CommentDao {
    QueryRunner queryRunner = new QueryRunner();   // 工具类

    /**
     * 新增评论
     */
    @Override
    public int add(Comment comment) throws SQLException {
        int num = 0;
        String sql = "insert into `comment` value (?,?,?,?,?);";
        num = queryRunner.update(DruidUtils.getConnection(), sql, comment.getHzId(), comment.getYgId(), comment.getPlComment(), comment.getPlDate());
        return num;
    }

    /**
     * 修改评论
     */
    @Override
    public int update(Comment comment) throws SQLException {
        int num = 0;
            String sql = "update comment set plComment =? where plId =?;";
            num = queryRunner.update(DruidUtils.getConnection(),sql,comment.getPlComment(), comment.getPlId());
        return num;
    }

    /**
     * 根据用户id删除评论
     */
    @Override
    public int deleteByhzId(Integer hzId) throws SQLException {
        int num = 0;
        String sql = "delete from comment where hzId =?;";
        num = queryRunner.update(DruidUtils.getConnection(), sql, hzId);
        return num;
    }

    /**
     * 根据评论id删除评论
     */
    @Override
    public int deleteByPlId(Integer plId) throws SQLException {
        int num = 0;
        String sql = "delete from comment where plId = 4;";
        num = queryRunner.update(DruidUtils.getConnection(), sql, plId);
        return num;
    }

    /**
     * 根据用户id分页查询评论
     */
    @Override
    public List<Comment> getCommentsByHzId(Integer hzId, Integer pageNo, Integer pageSize) throws SQLException {
        List<Comment> commentList = new ArrayList<Comment>();
        String sql = "SELECT plId,hzId,ygId,plComment,plDate FROM `comment` WHERE hzId =? order by plDate desc limit ?,?;";
        commentList = queryRunner.query(DruidUtils.getConnection(), sql, new BeanListHandler<Comment>(Comment.class), hzId, (pageNo - 1) * pageSize, pageSize);
        return commentList;
    }

    /**
     * 查询某用户下的评论总数
     */
    @Override
    public long getCountByHzId(Integer hzId) throws SQLException {
        long count = 0;
        String sql = "select count(0) as count from comment where hzId =?;";
        count = queryRunner.query(DruidUtils.getConnection(), sql, new ScalarHandler<>(), hzId);
        return count;
    }
}